package com.newlink.building.common_base.utils

import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.util.DisplayMetrics
import android.view.WindowInsets


/**
 * Created by xiaodong on 2022/8/1.
 */
object ScreenUtil {

    fun getScreenUsableHeight(activity: Activity): Int {
        val screenHeight = getScreenHeight(activity)
        NLog.e(":::::::::::::screenHeight:$screenHeight")
        val rect = Rect()
        activity.window.decorView.getWindowVisibleDisplayFrame(rect)
        val statusBarHeight = rect.top

        // 计算屏幕有效高度
        val usableHeight = screenHeight /*- statusBarHeight*/

        return usableHeight
    }

    fun getStatusBarHeight(activity: Activity): Int {
        val rect = Rect()
        activity.window.decorView.getWindowVisibleDisplayFrame(rect)
        val statusBarHeight = rect.top
        return statusBarHeight

    }

    fun getStatusBarHeightFromInsets(activity: Activity): Int {
        var statusBarHeight = 0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowInsets = activity.window.decorView.rootWindowInsets
            windowInsets?.let {
                statusBarHeight = it.getInsets(WindowInsets.Type.statusBars()).top
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val decorView = activity.window.decorView
            decorView.setOnApplyWindowInsetsListener { _, insets ->
                statusBarHeight = insets.systemWindowInsetTop
                insets
            }
        }
        return statusBarHeight
    }

    fun getScreenUsableHeightLandScape(activity: Activity): Int {
        val screenHeight = getScreenWidth(activity)
        NLog.e(":::::::::::::screenHeight:$screenHeight")
        val rect = Rect()
        activity.window.decorView.getWindowVisibleDisplayFrame(rect)
        val statusBarHeight = rect.top

        // 计算屏幕有效高度
        val usableHeight = screenHeight - statusBarHeight

        return usableHeight
    }

    fun getScreenWidth(activity: Activity): Int {
        val displayMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(displayMetrics)

        val screenWith = displayMetrics.widthPixels
        NLog.e(":::::::::::::screenHeight:$screenWith")
        return screenWith
    }

    fun getScreenHeight(activity: Activity): Int {
        val displayMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenHeight = displayMetrics.heightPixels
        NLog.e(":::::::::::::screenHeight:$screenHeight")
        return screenHeight
    }
}
